<?php

namespace app\base\controller\api;

use app\base\model\RedianTask;
use app\base\service\AlibailianService;
use app\base\service\TaskService;
use app\base\service\TikhubService;
use http\Message\Body;
use think\admin\Controller;
use app\base\model\AiDevice;
use app\base\controller\api\Auth;
use app\base\model\AiVoice;
use app\base\service\WsSendService;
use app\base\service\MinimaxService;
use app\base\service\CozeService;
use app\base\service\ChanjingService;
use app\base\service\XjyService;

/**
 * 设备相关
 * Class Login
 * @package app\store\controller
 */
class Test extends Controller
{
    public function sendWs()
    {  $device_id = input('device_id');
        foreach (["wxsph.js"] as $c){
            $content = [
                'type'=>1,
                'script_files'=>[$c],
                'script_file'=>$c,
                'data_id'=>12365,
                'is_update'=>1,
                'next_script_file'=>$c
            ];
            dump($content);
            $r = WsSendService::instance()->send($device_id,1,$content);
            dump($r);
        }


       // dump($r);
    }


    public function createALwb()
    {
        $system_content = "# 角色
你是一位专业且经验丰富的热点内容口播文本创作者，擅长把用户提供的热点内容标题与描述，转化成生动、极具感染力且符合口语化表达习惯的口播文本。输出的文本要纯粹简洁，不能包含语气描述、情绪表述、特殊音效、视频演示等无关内容。

## 技能
### 技能 1: 生成口播文本
1. 当用户提供热点内容的标题和描述后，深入剖析内容的性质、主题以及情感倾向。
2. 运用通俗易懂的语言，创作出一篇生动自然、逻辑清晰的口播文本，精准且流畅地将热点内容清晰传达给受众。

## 限制:
- 仅围绕用户提供的热点内容标题和描述展开文本创作，坚决拒绝回答与热点内容转化无关的话题。
- 所输出的文本必须清晰明确，语义不能模糊不清，也不能偏离合理范畴。
- 文本语言表达需严格符合大众口语习惯，避免使用过于生僻或复杂的词汇，不能包含开场音乐、插入音效、操作演示视频等其他无关内容 ，也不能包含任何语气描述、情绪表述之类的内容。 
- 创作过程中，尤其涉及真实人物时，需调用搜索或浏览器工具，在互联网上核实相关知识，确保信息来源准确可靠。";
        $user_content = "热点标题极氪001 We95 下单 热点描述极氪001 We95 下单 生成一段分钟的口播文本";
        $res = AlibailianService::instance()->createText(10000,$system_content,$user_content);
        dump($res);
    }

    public function minmaxclone()
    {
        MinimaxService::instance()->uploadFile(10000);


    }

    public function coze()
    {
        $data = [
            'keyword'=>"极氪007GT",
            'pages'=>1,
            'apiKey'=>"329f89155d44331afeaf39039581fe9e"
        ];
        $res = CozeService::instance()->runWorkflow("7502362477041106979",['input'=>["分享一个很顶级的心态“落子无悔”。上天不给你的，不管你怎么抓紧，他都会漏走，而给你的，不管你怎么失手，都一定会拥有。凡是过往，皆为序章，人生如棋，落子无悔。】 https://www.bilibili.com/video/BV11PXjYfEiM/?share_source=copy_web"]]);
        dump($res);

    }
    public function getWorkflowResult()
    {
        $execute_id = input('execute_id');
        $task_id = input('task_id');
        $task_run_log_id = input('task_run_log_id');
        $task = $this->app->db->name('redian_task')->where(['id'=>$task_id])->find();
        //$WorkflowResult = TaskService::instance()->textGenerate($task,$task_run_log_id);
        //$WorkflowResult = TaskService::instance()->getWorkflowResult($task,$execute_id,$task_run_log_id);
        //dump($WorkflowResult);exit;
        $res = CozeService::instance()->getWorkflowResult($execute_id,"7511747390979571749");
        $data = json_decode($res['data'][0]['output'],true);
       $task_datas =  json_decode($data['Output'],true);
        $this->success('success',['r'=>$res,'output'=>$task_datas['output']]);

    //    $this->success('success',$task_datas);
        exit;
        foreach ($task_datas['output'] as $k=>$t){
            if($t['code']==null ){
                $save_data = [
                    'content'=>$t['data']['content'],
                    'title'=>$t['data']['title'],
                    'task_id'=>1
                ];
                dump($save_data);
            }
        }
      //  $this->success('success',json_decode($data['Output']));
    }

    public function testces()
    {
        $i = 3;
        if ($i==1){
            $i = 2;
            dump(111);


        }
        if ($i==2){
            dump(222);
            $i = 3;
        }
        if ($i==3){
            dump(333);
            $i = 4;
        }
        if ($i==4){
            dump(444);
            $i = 5;
        }
        if ($i==5){
            dump(555);
            $i = 6;
        }
        if ($i==6){
            dump(666);
            $i = 7;
        }


    }

    public function testCj()
    {
       // ChanjingService::instance()->getAccessToken(10000);
        //$r = ChanjingService::instance()->getAvatarInfo(10000,input('id'));
        //$r = ChanjingService::instance()->createAvatarVideo(10000,input('id'),input('voice_url'));
        //$r = ChanjingService::instance()->getAvatarVideoInfo(10000,input('id'));
        $r = json_decode('{"trace_id":"445073805b6de8a804d5ed495b769c19","code":20003,"msg":"\u8749\u8c46\u4e0e\u65f6\u957f\u4e0d\u8db3"',true);
        dump($r);
    }

    public function testPush()
    {
        $task_info = input();
        $code= sysqueue($task_info['title']."推送数据到设备任务", "xbase:TaskPush",  10, $data = [
            'task_id'=>$task_info['task_id'],'task_run_log_id'=>$task_info['task_run_log_id']
        ], $rscript = 1, $loops = 0);
        dump($code);

    }

    public function tetAlBatch()
    {
        $data = input();
        $task = $this->app->db->name('redian_task')->where(['id'=>$data['task_id']])->find();
        $res = TaskService::instance()->batchSimilarity($task,$data['task_run_log_id']);

    }
    public function testAlBatchStatus()
    {
        $data = input();
        dump($data);
       // $r = TaskService::instance()->batchSimilarityResult($data['user_id'],$data['batch_id']);
        $r = AlibailianService::instance()->cancelBatch($data['user_id'],$data['batch_id']);
        dump($r);
    }
    public function testAldownloadBatch()
    {
        $data = input();

        $r = AlibailianService::instance()->downloadBatch($data['user_id'],$data['file_batch_output']);
        dump($r);
        dump(explode("\n",$r['data']));
        $data = explode("\n",$r['data']);
        foreach ($data as $k=>$v){
            dump(json_decode($v,true));
        }
    }

    public function testKeyword()
    {
        $video_keywords = "#qwq #eee #eee #fsdfs #fsfsa #gsdgfs #gfsdfs";
        $video_keywords_arr = explode('#',$video_keywords);
        dump($video_keywords_arr);
        if($c = count($video_keywords_arr)>5){
            $video_keywords = array_slice($video_keywords_arr,$c-6,5);
            $video_keywords = implode('#',$video_keywords);
        }
        dump("#".$video_keywords);

    }

    public function testgetAvatarList()
    {
        $user_id = input('user_id');
        $r = ChanjingService::instance()->getAvatarList($user_id);
        dump($r);

    }
    public function testgetAvatarVideoInfo()
    {
        $user_id = input('user_id');
            $video_id = input('video_id');
        $r = ChanjingService::instance()->getAvatarVideoInfo($user_id,$video_id);
        dump($r);

    }

    public function getVoicelist()
    {
        $user_id = input('user_id');
        $list = $this->app->db->name("ai_voice")->where( ['user_id'=>$user_id])->select()->toArray();
        foreach ($list as &$v){
            $v['other_data'] = json_decode($v['other_data'],true);
        }
         $this->success('success',$list);
    }


    public function extractContent() {
        $text = input('text');
        // 确保UTF-8编码处理
        if (!mb_check_encoding($text, 'UTF-8')) {
            $text = mb_convert_encoding($text, 'UTF-8', 'auto');
        }

        // 1. 移除所有导航项（包括中文和英文）
        $navItems = ['精选', '推荐', '关注', '朋友', '我的', '直播', '放映厅', '短剧',
            '下载', '广告投放', '用户服务协议', '隐私政策', '账号找回',
            '联系我们', '加入我们', '营业执照', '友情链接', '站点地图', '电商',
            '搜索', '充值', '客户端', '壁纸', '通知', '私信', '投稿',
            '登录', '综合', '视频', '用户', '多列', '单列', '筛选',
            '常见问题', '意见反馈', '首页', '发现', '消息', '个人中心',
            'Home', 'Discover', 'Message', 'Profile', 'Trending', 'Following'];

        // 创建导航项的正则模式（精确匹配）
        $navPattern = '/\b(' . implode('|', array_map(function($item) {
                return preg_quote($item, '/');
            }, $navItems)) . ')\b/u';

        $text = preg_replace($navPattern, '', $text);

        // 2. 移除日期和时间格式
        $text = preg_replace('/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/u', '', $text); // 2022-06-16 00:00:00
        $text = preg_replace('/\d{4}年\d{1,2}月\d{1,2}日/u', '', $text);           // 2025年5月22日
        $text = preg_replace('/\d{1,2}月\d{1,2}日/u', '', $text);                  // 5月22日
        $text = preg_replace('/\d{1,2}:\d{2}/u', '', $text);                       // 00:09

        // 3. 移除所有版权和许可证信息
        $text = preg_replace('/\d{4} © .*/u', '', $text);
        $text = preg_replace('/京(公网安备|ICP).*/u', '', $text);
        $text = preg_replace('/(许可证|备案|证号|安备|文号|网文|证书|资质|备案号|注册号|执照|号-\d+).*/u', '', $text);

        // 4. 移除数字统计和来源标注
        $text = preg_replace('/[\d.,]+万?/', '', $text); // 12.4万, 1.8万
        $text = preg_replace('/@\s*[\w·]+(\s*·\s*[\d月日]+)?/u', '', $text); // @潮新闻 · 5月22日

        // 5. 移除特殊符号和标签
        $text = preg_replace('/#\S+/u', '', $text); // 移除话题标签
        $text = preg_replace('/\s*·\s*/u', ' ', $text); // 移除分隔点
        $text = preg_replace('/\s*&\s*/u', ' ', $text); // 移除&符号

        // 6. 移除重复的"word"序列和乱码
        $text = preg_replace('/\b(word\s*){3,}/iu', '', $text);
        $text = preg_replace('/mmMwWLliI0fiflO&\s*\d+/u', '', $text);

        // 7. 移除换行符和多余空格
        $text = preg_replace('/\R/u', ' ', $text); // 所有换行符替换为空格
        $text = preg_replace('/\s{2,}/u', ' ', $text); // 多个空格合并为一个

        // 8. 移除残留的短词和符号
        $text = preg_replace('/\b(\w{1,2}|\d+)\b/u', '', $text); // 移除1-2字母的单词和纯数字
        $text = preg_replace('/[^\p{L}\p{N}\s.,!?;:"\'()-]/u', '', $text); // 只保留字母、数字、标点和空格
        return trim($text);
    }
    public function createAccountMonitor()
    {
        $task['home_page'] = input('home_page');
        $r = TaskService::instance()->createAccountMonitor($task);
        dump($r);
    }
    public function getAccountMonitor()
    {
        $execute_id = input('execute_id');
        $task['user_id'] = 1;
        $r = CozeService::instance()->getWorkflowResult($execute_id,7511634985201336357);
       // $r = TaskService::instance()->getAccountMonitorResult($task,$execute_id);
        dump($r);
    }

    //对标账号提取部分
    public function getXhsUserNotes()
    {
        $task['home_page'] = input('home_page');
        $r = TaskService::instance()->getXhsUserNotes($task);
        $this->success('success',$r);
    }
    public function getXhsNoteInfo()
    {
        $id = input('id');
        $r = TikhubService::instance()->getXhsNoteInfoById($id);
        $this->success('success',$r);
    }
    public function getDyUserVideos()
    {
        $task['home_page'] = input('home_page');
        $home_page = $task['home_page'];
        if (preg_match('/\/user\/([A-Fa-f0-9]+)[\W_]*/i', $home_page, $matches)) {
            $user_id = $matches[1];
        } else {
            // 处理带参数的URL
            $path = explode('?', $home_page)[0];
            $segments = explode('/', $path);
            $user_id = end($segments);
        }
        if(empty($user_id)){
            return ['code'=>-1,'msg'=>'抖音账号ID获取失败,请检查主页URL是否正确'];
        }
        dump($user_id);
        $res = TikhubService::instance()->getDyUserVideos($user_id);
        $this->success('success',$res);





        $r = TaskService::instance()->getDyUserNotes($task);
        $this->success('success',$r);
        exit;
        $user_id = input('user_id');
        $r = TikhubService::instance()->getDyUserVideos($user_id);
        $this->success('success',$r);
    }

    public function submitVideoLanguage()
    {
        $id = input('id');
        $task = RedianTask::mQuery()->where(['id'=>$id])->find();
        $r = TaskService::instance()->createVideoAudioText($task,440);
        //$r = AlibailianService::instance()->submitVideoLanguage(10000,$url);
        dump($r);
    }
    public function queryVideoLanguage()
    {
        $timeStr = "01:50";
        list($minutes, $seconds) = explode(':', $timeStr);
        $totalSeconds = (int)$minutes * 60 + (int)$seconds;
        dump($totalSeconds);exit;
        $task_id = input('task_id');
        $r = AlibailianService::instance()->queryVideoLanguage(10000,$task_id);
        dump($r);
    }

    public function createAvatarVideoByText()
    {
        $data = input();
        $r = ChanjingService::instance()
            ->createAvatarVideoByText($data['user_id'],$data['avatar_id'],$data['text'],$data['audio_man']);
        dump($r);
        $this->success('success',$r);
    }
    public function getAvatarVideoByText()
    {
        $data = input();
        $r = ChanjingService::instance()
            ->getAvatarVideoInfo($data['user_id'],$data['video_id']);
        dump($r);

    }

    public function testcozeJWT()
    {
        $url = ['2.02 02/01 Kwf:/ v@F.hb 53集 | 一口气看完一整部恐怖片《森林恶鬼》 # 电影解说 # 恐怖·电影· # 恐怖片 # 瓜子二手车  https://v.douyin.com/vNx-2a205S8/ 复制此链接，打开Dou音搜索，直接观看视频！'];
        $res = CozeService::instance()->runWorkflow("7502362477041106979",['input'=>$url]);
        dump($res);exit;
        return $res;
        $s =  CozeService::instance()->getWorkflowResult(7511634985201336357);
        dump($s);
        CozeService::instance()->getAuthorization();

    }
    //手动推送数据测试
    public function sendWSDevice()
    {
        $id = input('id');
        $device_id = input('device_id');
        $data = $this->app->db->name("redian_data")->where('id',$id)->find();
        //$script_files = json_decode($data['run_script'], true);
//        if(count($script_files)>1){
//            $script_file = $script_files[0];
//            $next_script_file = $script_files[1];
//        }else{
//            $next_script_file = '';
//        }
        $content = [
            'type'=>1,
            'script_files'=>["kaipav3.js","wxsphv3.js","douyinv3.js"],
            'script_file'=>"kaipav3.js",
            'next_script_file'=>"",
            'data_id'=>$id,
            'is_update'=>1
        ];
        WsSendService::instance()->send($device_id,1,$content);
        $this->success('success');

    }

    public function sendWSDevicev2(){
        $id = input('id');
        $device_id = input('device_id');
        $data = $this->app->db->name("redian_data")->where('id',$id)->find();
        $script_file = json_decode($data['run_script'], true)[0];
        $script_file1 = "test1.js";
        $script_file2 = "test2.js";
        $content = [
            'type'=>1,
            'script_files'=>[$script_file1,$script_file2],
            'script_file'=>$script_file1,
            'next_script_file'=>"",
            'data_id'=>$id,
            'is_update'=>1
        ];
        WsSendService::instance()->send($device_id,1,$content);
    }

    //手动推送数据测试
    public function sendWSDevice3()
    {
        $id = input('id');
        $device_id = input('device_id');
        $data = $this->app->db->name("redian_data")->where('id',$id)->find();
        $script_files = json_decode($data['run_script'], true);
        if(count($script_files)>1){
            $script_file = $script_files[0];
            $next_script_file = $script_files[1];
        }else{
            $next_script_file = '';
        }
        $content = [
            'type'=>1,
            'script_files'=>["wxsphv32.js"],
            'script_file'=>"wxsphv32.js",
            'next_script_file'=>"",
            'data_id'=>$id,
            'is_update'=>1
        ];
        WsSendService::instance()->send($device_id,1,$content);
        $this->success('success');

    }

    //测试小甲鱼高级音频
    public function agentVideo()
    {
        exit;
        $list = $this->app->db->name("ai_voice")->where(['type'=>2,'platform_name'=>"小甲鱼",'status'=>3])

            ->where('id','>',122)->order('id desc')->column('id');
        $this->app->db->name("ai_voice")->whereIn('id',$list)->update(['status'=>2]);
        $code = sysqueue("创建小甲鱼视频模板任务","xbase:CreateXjyVideoTemplate",1,['id'=>implode(',',$list)],$rscript = 1, $loops = 0);
        dump($code);exit;
        foreach ($list as $item){
//            $r = XjyService::instance()->createAvatar($item['name'],$item['file_url']);
//            if($r['code']==0){
//                $this->error($r['msg']);
//            }
//            $item['code'] = $r['data'];
            $this->app->db->name("ai_voice")->where('id',$item['id'])->update(['code'=>$item['code'],'status'=>2]);
            $code = sysqueue("{$item['name']}创建小甲鱼视频模板任务","xbase:CreateXjyVideoTemplate",1,['id'=>$item['id']],$rscript = 1, $loops = 0);
        }
        dump($code);

    }


}
